import app from '../index.js';
var  E ={};
/*
* 创建沿边行走的光点
* */
E.light = function () {
  let radius = 2, //光点半径
      lasttime = 0,//上次的时间
      color = 'lightgreen',//光点颜色
      speed = 50,
      cleared = false;

  function _light(sel) {
    sel.each(function (d) {
      console.log(d);
      let t = app.d3.select(this);
      let that = this;
      //此方法的调用必须是有线的外层有g
      app.d3.select(t.node().parentNode)
      .append('circle')
      .attr('class','effect-light')
      .attr('r',radius)
      .attr('fill',function (d) {
        return typeof color === 'function' ? color(d) :color
      })
      .datum({
        path: that,
        walked:0
      });
      cleared = false;
      lasttime = 0;
      app.d3.timer(update);
    });
  };
  function update(t) {
    if(cleared) {return true};
    let effects = app.d3.selectAll('.effect-light');
    let moved  = (t - lasttime) * speed /1000;
    effects.each(function (d,i) {
      let total = d.path.getTotalLength();
      d.walked += moved;
      if(d.walked > total){
        d.walked = 0;
      }
      // d.walked = d.walked % total;
      let point = d.path.getPointAtLength(d.walked);
      app.d3.select(this)
      .attr('cx', point.x)
      .attr('cy', point.y)
      ;
    });
    lasttime = t;
  };


  _light.clear = function () {
    cleared = true;
    app.d3.selectAll('.effect-light').remove();
    app.d3.timerFlush();
  };
  _light.speed = function (s) {
    return s ? (speed = s, this) : s;
  };
  _light.radius = function (r) {
    return r ? (radius = r, this) : radius;
  };
  _light.color = function (c) {
    return c ? (color = c, this) : color;
  }
  return _light;

};

export default E;